/**
 * 
 */
package org.smvc.framework.aop;

import java.io.FileOutputStream;

import org.objectweb.asm.ClassReader;
import org.smvc.framework.aop.interceptor.Interceptor;

import net.sf.cglib.core.ClassNameReader;
import net.sf.cglib.proxy.Enhancer;

/**
 * 生成代理工厂
 * @category
 * @author xiangyong.ding@weimob.com
 * @since 2017年9月25日 下午11:51:58
 */
public class ProxyFactory
{

	public static <T> T getInstance(Class<T> targetClass, Interceptor[] interceptors)
	{
		Enhancer en = new Enhancer(); // Enhancer用来生成一个原有类的子类
		// 进行代理
		en.setSuperclass(targetClass);

		// 设置织入逻辑
		en.setCallback(new Callback(interceptors));
		// 生成代理实例
		@SuppressWarnings("unchecked")
		T instance = (T) en.create();
		try
		{
			byte[] bytes = en.getStrategy().generate(en);
			String className = ClassNameReader.getClassName(new ClassReader(bytes));
			System.out.println(className);
			FileOutputStream os = new FileOutputStream(className+".class");
			os.write(bytes);
			os.close();
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		return instance;
	}
}